<template>
  <div class="app-container">
    <el-form :model="searchForm" ref="searchFormRef" size="small" inline v-show="showSearch">
      <el-form-item label="角色名称" prop="like.name">
        <el-input v-model="searchForm.like.name" placeholder="请输入角色名称" clearable class="w-150px"/>
      </el-form-item>
      <el-form-item label="权限字符" prop="like.role_key">
        <el-input v-model="searchForm.like.role_key" placeholder="请输入权限字符" clearable class="w-150px"/>
      </el-form-item>
      <el-form-item label="数据权限" prop="where.data_scope">
        <el-select v-model="searchForm.where.data_scope" placeholder="数据权限" clearable class="w-160px">
          <el-option v-for="scope in dataScopeOptions" :key="scope.value" :label="scope.label" :value="scope.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="where.status">
        <el-select v-model="searchForm.where.status" placeholder="角色状态" clearable class="w-130px">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="mb-8px reset">
      <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPerm="['system:role:add']">新增</el-button>
      <el-button type="success" plain icon="el-icon-edit" @click="handleEdit" v-hasPerm="['system:role:edit']" :disabled="ids.length !== 1">修改</el-button>
      <el-button type="danger" plain icon="el-icon-delete" @click="handleDelete" v-hasPerm="['system:role:delete']" :disabled="!ids.length">删除</el-button>
      <el-button type="warning" plain icon="el-icon-download" @click="handleExport" v-hasPerm="['system:role:export']">导出</el-button>
      <right-toolbar :showSearch.sync="showSearch" @refresh="getList" />
    </div>

    <el-table v-loading="loading" :data="listData" @selection-change="handleSelection">
      <el-table-column type="selection" align="center" min-width="50" :selectable="canSelect"/>
      <el-table-column label="编号" align="center" prop="id" min-width="60" />
      <el-table-column label="角色名称" align="center" prop="name" show-overflow-tooltip min-width="150" />
      <el-table-column label="权限字符" align="center" prop="role_key" show-overflow-tooltip min-width="120" />
      <el-table-column label="数据权限" align="center" min-width="150">
        <template v-slot="{ row }">{{ row.data_scope | dataScopeLabel }}</template>
      </el-table-column>
      <el-table-column label="顺序" align="center" prop="list_sort" min-width="60" />
      <el-table-column label="状态" align="center" min-width="80">
        <template v-slot="{ row }">
          <el-switch v-model="row.status" active-value="1" inactive-value="0" @change="handleStatus(row)" v-if="statusPerm"/>
          <dict-tag :options="dict.type.sys_normal_disable" :value="row.status" v-else/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="140">
        <template v-slot="{ row }">
          <el-tooltip content="修改" placement="top" v-hasPerm="['system:role:edit']" v-if="row.id !== rootRole">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(row)" ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-hasPerm="['system:role:delete']" v-if="row.id !== rootRole">
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(row)"></el-button>
          </el-tooltip>
          <el-tooltip content="数据权限" placement="top" v-hasPerm="['system:role:data-scope']">
            <el-button type="text" icon="el-icon-circle-check" @click="handleDataScope(row)"></el-button>
          </el-tooltip>
          <el-tooltip content="分配用户" placement="top" v-hasPerm="['system:role:auth-list']">
            <el-button type="text" icon="el-icon-user" @click="handleAuthUser(row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="searchForm.pageNum" :limit.sync="searchForm.pageSize" @pagination="getList"/>
    <RoleForm v-model="formShow" :id="formId" @submit="getList" v-if="formShow"/>
    <DataScope v-model="dataScopeShow" :id="dataScopeId" @submit="getList" v-if="dataScopeShow"/>
  </div>
</template>

<script>
import { checkPerm } from '@/utils/auth'
import { listRoleApi, delRoleApi, changeStatusApi, exportRoleApi } from "@/api/system/role"
import RoleForm from './form.vue'
import DataScope from './dataScope.vue'
import { dataScopeOptions, getDataScopeLabel } from './script'

export default {
  name: "AuthUser",
  dicts: ['sys_normal_disable'],
  components: { DataScope, RoleForm },
  filters:{
    dataScopeLabel(v){
      return getDataScopeLabel(v)
    }
  },
  data() {
    return {
      loading: true,
      ids: [],
      showSearch: true,
      total: 0,
      listData: [],
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        like: { name: undefined, role_key: undefined } ,
        where: { status: undefined, data_scope: undefined },
        orderByColumn: 'list_sort'
      },
      formId: null,
      formShow: false,
      dataScopeOptions: dataScopeOptions,
      dataScopeShow: false,
      dataScopeId: null,
    }
  },
  computed: {
    rootRole() {
      return this.$store.getters.config?.root_role_id || 0
    },
    statusPerm() {
      return checkPerm('system:role:status')
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listRoleApi(this.searchForm).then(res => {
        this.listData = res.list
        this.total = res.total
        this.loading = false
      })
    },
    search() {
      this.searchForm.pageNum = 1
      this.getList()
    },
    reset() {
      this.resetForm('searchFormRef')
      this.search()
    },
    handleAdd() {
      this.formId = null
      this.formShow = true
    },
    handleEdit(row) {
      this.formId = row?.id || (this.ids.length === 1 ? this.ids[0] : null)
      if (!this.formId) return this.$modal.msgWarning('没有选中操作数据')
      this.formShow = true
    },
    handleDelete(row) {
      const roleIds = row?.id || this.ids.join(',')
      if(!roleIds) return this.$modal.msgWarning('没有选中操作数据')
      this.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(() => {
        return delRoleApi(roleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    handleStatus(row) {
      if (!row || !row.id) return this.$modal.msgWarning('没有选中操作数据')
      const text = row.status === "1" ? "启用" : "停用"
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"角色吗？').then(() => {
        return changeStatusApi(row.id, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    handleSelection(selection) {
      this.ids = selection.map(item => item.id)
    },
    handleDataScope(row) {
      this.dataScopeId = row.id || ''
      if (!this.dataScopeId) return this.$modal.msgError('参数缺失')
      this.dataScopeShow = true
    },
    handleAuthUser: function(row) {
      const roleId = row.id || ''
      if(!roleId) return this.$modal.msgWarning('参数错误')
      this.$router.push({ name: 'AuthUser', params: { roleId: roleId } })
    },
    /** 导出按钮操作 */
    handleExport() {
      exportRoleApi(this.searchForm)
    },
    canSelect(row) {
      return row.id !== this.rootRole
    }
  }
}
</script>
